import axios from 'axios'
import cache from '@/utils/cache'
import {baseURL} from '@/server/config'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: baseURL,
  // 超时
  timeout: 10000
})

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// request拦截器
service.interceptors.request.use(config => {

  if (cache.getToken()) {
    config.headers['token'] = cache.getToken() // 让每个请求携带自定义token 
  }
 
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

service.interceptors.response.use(
	async (response) => {
		const res = response.data
		// 响应成功
		if (res.code === 200) {
			return res;
		}else if(res.code === 0){
			return res;
		}else if(res.code==401){
			location.href='/login'
			return Promise.reject('')
		}

		return Promise.reject(new Error(res.msg || 'Error'))
	},
	error => {
		console.log(error);
	}
)

export default service